﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TjZheng.Core.Process.Filter;
using TjZheng.Core.Process.Handle;
using TjZheng.Core.Process.Helper;
using TjZheng.Framework;
using TjZheng.Web.Helper;

namespace TjZheng.WeiXin.SDK.Pay
{
    public class UnifiedOrderProcessHandle : ProcessHandle
    {
        public override void OnExecuting(ProcessExecutingContext filterContext)
        {
            ProcessHelper.CheckProcessFilterContext(filterContext);
            UnifiedOrderProcessContext objUnifiedOrderProcessContext = filterContext.ProcessContext as UnifiedOrderProcessContext;
            if (objUnifiedOrderProcessContext == null)
            {
                throw new WxPayException("缺少统一下单接口上下文UnifiedOrderProcessContext为空！");
            }

            objUnifiedOrderProcessContext.CheckIntputWxPayPackage();
            objUnifiedOrderProcessContext.CheckMerchantInfo();

            WxPayPackage objWxPayPackage = objUnifiedOrderProcessContext.IntputWxPayPackage;

            //检测必填参数
            if (!objWxPayPackage.IsValueSet("out_trade_no"))
            {
                throw new WxPayException("缺少统一下单接口必填参数out_trade_no！");
            }
            if (!objWxPayPackage.IsValueSet("body"))
            {
                throw new WxPayException("缺少统一下单接口必填参数body！");
            }
            if (!objWxPayPackage.IsValueSet("total_fee"))
            {
                throw new WxPayException("缺少统一下单接口必填参数total_fee！");
            }
            if (!objWxPayPackage.IsValueSet("trade_type"))
            {
                throw new WxPayException("缺少统一下单接口必填参数trade_type！");
            }

            //关联参数
            if (Convert.ToString(objWxPayPackage.GetValue("trade_type")) == "JSAPI" && !objWxPayPackage.IsValueSet("openid"))
            {
                throw new WxPayException("统一下单接口中，缺少必填参数openid！trade_type为JSAPI时，openid为必填参数！");
            }
            if (Convert.ToString(objWxPayPackage.GetValue("trade_type")) == "NATIVE" && !objWxPayPackage.IsValueSet("product_id"))
            {
                throw new WxPayException("统一下单接口中，缺少必填参数product_id！trade_type为JSAPI时，product_id为必填参数！");
            }
        }

        public override InvokeResult Execute(ProcessContext objProcessContext)
        {
            UnifiedOrderProcessContext objUnifiedOrderProcessContext = objProcessContext as UnifiedOrderProcessContext;
            WxPayPackage objWxPayPackage = objUnifiedOrderProcessContext.IntputWxPayPackage;
            string xml = objWxPayPackage.ConvertToXml();
            
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            WxPayPackage objOutputWxPayPackage = url.CreateWxPayApiRequest(objWxPayPackage, objUnifiedOrderProcessContext.MerchantInfo);

            objUnifiedOrderProcessContext.OutputWxPayPackage = objOutputWxPayPackage;
            objUnifiedOrderProcessContext.CheckOutputWxPayPackage();

            InvokeResult objInvokeResult = new InvokeResult
            {
                Data = objUnifiedOrderProcessContext.OutputWxPayPackage
            };

            //判断是否签名
            if (objUnifiedOrderProcessContext.IntputWxPayPackage.IsValueSet("sign"))
            {
                //2015-06-29 错误是没有签名
                if (Convert.ToString(objUnifiedOrderProcessContext.OutputWxPayPackage.GetValue("return_code")) != "SUCCESS")
                {
                    return objInvokeResult;
                }
                objUnifiedOrderProcessContext.OutputWxPayPackage.CheckSign(objUnifiedOrderProcessContext.MerchantInfo.MKey);
            }

            return objInvokeResult;
        }

        /// <summary>
        /// 测速上报
        /// </summary>
        /// <param name="objOutputPackageResult"></param>
        public virtual void ReportCostTime(WxPayPackage objOutputPackageResult)
        { 
            
        }

        public override void OnExecuted(ProcessExecuedContext filterContext)
        {
            ProcessHelper.CheckProcessFilterContext(filterContext);
            UnifiedOrderProcessContext objUnifiedOrderProcessContext = filterContext.ProcessContext as UnifiedOrderProcessContext;

            WxPayPackage objOutputWxPayPackage = objUnifiedOrderProcessContext.OutputWxPayPackage;

            if (objUnifiedOrderProcessContext.MerchantInfo.ReportLevel == 2)
            {
                this.ReportCostTime(objOutputWxPayPackage);
            }
        }

        public override void OnException(ExceptionFilterContext filterContext)
        {
            if (filterContext.Exception is WxPayException)
            {
                WxPayException objWxPayException = filterContext.Exception as WxPayException;
                filterContext.Result = new InvokeResult 
                {
                    ResultCode = "WxPayException",
                    ResultMessage = objWxPayException.Message
                };
                filterContext.ExceptionHandled = true;
            }
        }
    }
}
